package com.haoze.nurseapp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.haoze.common.config.RedisUtil;
import com.haoze.common.enumeration.StateEnum;
import com.haoze.common.exception.ServiceException;
import com.haoze.common.model.OrdersFileIndexDataEntity;
import com.haoze.common.model.OrdersFileIndexEntity;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.JSONUtils;
import com.haoze.common.utils.UUIDUtil;
import com.haoze.nurseapp.dao.*;
import com.haoze.nurseapp.dto.NodeInfoDTO;
import com.haoze.nurseapp.model.EmrCatalogEntity;
import com.haoze.nurseapp.model.EmrTemplateDetailRoleEntity;
import com.haoze.nurseapp.model.EmrTemplateEntity;
import com.haoze.nurseapp.service.NurseFileIndexService;
import com.haoze.nurseapp.service.feign.DataSetValueCommonService;
import com.haoze.nurseapp.vo.Element;
import com.haoze.nurseapp.vo.EmrFile;
import com.haoze.nurseapp.vo.EmrFileData;
import com.haoze.nurseapp.vo.TaskNodeVO;
import oracle.sql.TIMESTAMP;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.jasypt.commons.CommonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuples;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Clob;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
public class NurseFileIndexServiceImpl implements NurseFileIndexService {

    private static final Logger logger = LoggerFactory.getLogger(NurseFileIndexServiceImpl.class);

    @Autowired
    OrdersFileIndexMapper ordersFileIndexMapper;

    @Resource
    TaskExecuteMapper taskExecuteMapper;

    @Autowired
    OrdersFileIndexDataMapper ordersFileIndexDataMapper;

    @Autowired
    EmrTemplateMapper emrTemplateMapper;

    @Autowired
    EmrCatelogMapper emrCatelogMapper;

    @Autowired
    EmrCatalogMapper emrCatalogMapper;

    @Resource
    private EmrTemplateMapper templateMapper;

    @Resource
    private RedisUtil redisUtil;

    //签名数据元
    private static List<String> signElements;

    @Value("${spring.profiles.active}")
    private String activeProfile;

    @Resource
    private SqlSessionFactory sqlSessionFactory;

    @Resource
    private DataSetValueCommonService dataSetValueCommonService;

    @Override
    public EmrFile getFileIndex(String emrFileId) {
        //to-do
        OrdersFileIndexEntity emrFileIndex = ordersFileIndexMapper.selectByPrimaryKey(emrFileId);
        String emrType = ordersFileIndexMapper.getEmrType(emrFileId);
        if (emrFileIndex == null) {
            return null;
        }
        EmrFile emrFile = getDataFromDB(emrFileIndex, emrType);
        //实时刷新引用数据
        List<EmrFileData> flatList = flatConvert(emrFile.getEmrFileDataList());
        refreshQuteData(flatList, emrFileIndex);
//        //返回默认病区信息
//        if(!StringUtils.hasLength(emrFile.getEmrFileIndexEntity().getWardDeptId())){
//            Map<String, String> patientInfo = ordersFileIndexMapper.getPatientInfo(emrFileIndex.getInpatNum());
//            if(null!=patientInfo){
//                emrFile.getEmrFileIndexEntity().setWardDeptId(patientInfo.get("wardDeptId"));
//            }
//        }
        emrFile.clearTempInfo();
        Map<String, Object> attributes = new HashMap<>();
        attributes.put("emrType", emrFile.getEmrType());
//        logger.info("目录id：", emrFileIndex.getTplId());
        EmrCatalogEntity catalog = emrCatalogMapper.selectByTplId(emrFileIndex.getTplId());
        attributes.put("ctlId", catalog.getCtlId());
        attributes.put("ctlName", catalog.getCtlName());
        emrFile.setAttributes(attributes);
        return emrFile;
    }

    /**
     * 获取模板中引用的数据集数据
     *
     * @param tplId    模板ID
     * @param inpatNum 住院号
     * @param reqNum   电子申请单编号
     * @param serialNo 序列号
     * @param emrType  病历类型
     * @return
     */
    private List<CompletableFuture<Tuple2<String, JSONObject>>> getDatasetMap(String tplId, String inpatNum, String reqNum, String serialNo, String emrType) {
        List<Map<String, String>> datasetList = ordersFileIndexMapper.getDatasetListNew(tplId);
        List<CompletableFuture<Tuple2<String, JSONObject>>> futures = datasetList.stream().map(dataset -> {
            return CompletableFuture.supplyAsync(() -> {
                long t1 = System.currentTimeMillis();
                String datasetId = dataset.get("DATASET_ID");
                String url = dataset.get("READ_SERVICE");
                if (org.apache.commons.lang3.StringUtils.isBlank(url)) {
                    return null;
                }
                Map<String, String> params = new HashMap<String, String>();
                params.put("DATASET_ID", datasetId);
                params.put("inpatNum", inpatNum);
                if (org.apache.commons.lang3.StringUtils.isNotBlank(reqNum)) {
                    params.put("reqNum", reqNum);
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(serialNo)) {
                    params.put("serialNo", serialNo);
                }
                params.put("emrType", emrType);
                Result result = dataSetValueCommonService.commonDataSetValue(params);
                long t2 = System.currentTimeMillis();
                logger.info("查询第三方接口 {} 数据耗时：{} ms", url, t2 - t1);
                if (result.getCode() == 200) {
                    JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(result.getData()));
                    return Tuples.of(datasetId, data);
                } else {
                    return null;
                }
            });
        }).collect(Collectors.toList());
        return futures;
    }

    private void refreshQuteData(List<EmrFileData> list, OrdersFileIndexEntity emrFileIndex) {
        List<CompletableFuture<Tuple2<String, JSONObject>>> datasetFutures = getDatasetMap(emrFileIndex.getTplId(), emrFileIndex.getInpatNum(), "", "", "");
        Map<String, Map<String, Object>> datasetMap = new HashMap<>();
        try {
            CompletableFuture.allOf(datasetFutures.toArray(new CompletableFuture[0])).thenApply(v -> datasetFutures.stream().map(CompletableFuture::join)
                    .collect(Collectors.toList())).get().stream().filter(Objects::nonNull).forEach(tuple2 -> datasetMap.put(tuple2.getT1(), tuple2.getT2()));
        } catch (Exception e) {
            logger.error("调用第三方接口报错", e);
        }
        list.stream().forEach(data ->
        {
            OrdersFileIndexDataEntity dataEntity = data.getFileIndexDataEntity();
            // 引用其他病历 新版本
            if (StringUtils.hasLength(dataEntity.getQuoteTplDetailId()) && dataEntity.getQuoteTplDetailId().startsWith("[[")) {
                JSONArray priorityArray = JSONArray.parseArray(dataEntity.getQuoteTplDetailId());
                for (Object priorityObj : priorityArray) {
                    JSONArray totalArray = (JSONArray) priorityObj;
                    boolean isFound = totalArray.stream().map(parallelingObj -> {
                        String inpatNum = emrFileIndex.getInpatNum();
                        List<OrdersFileIndexDataEntity> refDataList;
                        JSONObject quoteRule = (JSONObject) parallelingObj;
                        String emrType = quoteRule.getString("emrType");
                        String isRefresh = quoteRule.getString("isRefresh");
                        if (!"Y".equals(isRefresh)) {
                            //不需要实时刷新获取病历不需要重新引用
                            return false;
                        }
                        if (StringUtils.isEmpty(emrType)) {
                            logger.info("缺少目录类型，无法引用。");
                            return false;
                        }

                        refDataList = ordersFileIndexMapper.queryRefData(quoteRule.getString("quoteId"), emrType, inpatNum, quoteRule.getString("quoteAll"), quoteRule.getString("isDesc"));
                        if (refDataList.isEmpty()) { // 引用节点已不存在 忽略
                            return false;
                        }
                        return IntStream.range(0, refDataList.size()).mapToObj(idx -> {
                            OrdersFileIndexDataEntity refData = refDataList.get(idx);
                            if ("Y".equals(quoteRule.getString("oneToOne"))) { // 点对点引用
                                if (StringUtils.isEmpty(refData.getDataValue())) {
                                    return false;
                                }
                                dataEntity.setDataValue(refData.getDataValue());
                                dataEntity.setDataCode(refData.getDataCode());
                                ordersFileIndexDataMapper.updateByPrimaryKeySelective(dataEntity);
                                return true; // 有数据 才算找到
                            }
                            return true;
                        }).reduce(false, (accumulatorBoolean, nextBoolean) -> accumulatorBoolean || nextBoolean);
                    }).reduce(false, (accumulatorBoolean, nextBoolean) -> accumulatorBoolean || nextBoolean);
                    // 如果已经引用到数据 终止循环
                    if (isFound)
                        break;
                }
            }
        });


    }

    /**
     * 保存数据元
     *
     * @param emrFileDataList
     */
    private List<EmrFileData> flatConvert(List<EmrFileData> emrFileDataList) {
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        Stack<EmrFileData> stack = new Stack<>();
        List<EmrFileData> dataList = new ArrayList<>();
        for (int i = 0; i < emrFileDataList.size(); i++) {
            EmrFileData topEmrFileData = emrFileDataList.get(i);
            topEmrFileData.getFileIndexDataEntity().setParentFileIndexDataId("");
            topEmrFileData.getFileIndexDataEntity().setSortId(i + 1);
            stack.push(topEmrFileData);

            while (!stack.empty()) {
                EmrFileData emrFileData = stack.pop();
                OrdersFileIndexDataEntity dataEntity = emrFileData.getFileIndexDataEntity();
                if (dataEntity.getCreateTime() == null) {
                    dataEntity.setCreateTime(currentTime);
                    dataEntity.setModifyTime(currentTime);
                } else {
                    dataEntity.setCreateTime(currentTime);
                }
                //判断elementId是否为空，同时校验值域字典
                if (StringUtils.isEmpty(dataEntity.getElementId())) {
                    if (StringUtils.hasLength(dataEntity.getDataValue())) {
                        Element element = emrFileData.getElement();
                        String elementId;
                        if (StringUtils.hasLength(element.getVarCode())) {
                            elementId = templateMapper.getSysElementIdByVarCode(element.getVarCode());
                        } else {
                            elementId = templateMapper.getSysElementIdByVarCode(this.MB_WB);
                        }
                        if (StringUtils.isEmpty(elementId))
                            throw new ServiceException(dataEntity.getDataValue() + "没有数据元id,无法保存！");
                        else
                            dataEntity.setElementId(elementId);
                    } else {
                        String elementId = templateMapper.getSysElementIdByVarCode(this.MB_WB);
                        if (StringUtils.isEmpty(elementId))
                            throw new ServiceException(dataEntity.getDataValue() + "没有数据元id,无法保存！");
                        else
                            dataEntity.setElementId(elementId);
                    }
                }
                //签名保存职称
                if (StringUtils.isEmpty(signElements)) {
                    signElements = ordersFileIndexMapper.getSignElementIds();
                }
                if (signElements.contains(dataEntity.getElementId())) {
                    if (StringUtils.hasLength(dataEntity.getDataCode())) {
                        String groupName = ordersFileIndexMapper.getGroupNameByUserId(dataEntity.getDataCode());
                        dataEntity.setExtendedField(groupName == null ? "职称未知" : groupName);
                    }
                }
                // 废弃部分属性 减少缓存时的体积
                emrFileData.setRoleEntity(null);

                dataList.add(emrFileData);

                List<EmrFileData> subEmrFileDataList = emrFileData.getEmrFileDataList();
                int j = subEmrFileDataList.size();
                while (--j >= 0) {
                    subEmrFileDataList.get(j).getFileIndexDataEntity().setSortId(j + 1);
                    subEmrFileDataList.get(j).getFileIndexDataEntity().setParentFileIndexDataId(dataEntity.getFileIndexDataId());
                    stack.push(subEmrFileDataList.get(j));
                }
            }
        }
        return dataList;
    }


    private EmrFile getDataFromDB(OrdersFileIndexEntity emrFileIndex, String emrType) {
        EmrFile emrFile;
        emrFile = new EmrFile();
        emrFile.setEmrFileIndexEntity(emrFileIndex);
        emrFile.setEmrType(emrType);
        emrFile.setPrintType(ordersFileIndexMapper.getPrintType(emrFileIndex.getEmrFileId()));

        List<Map<String, String>> observations = ordersFileIndexMapper.queryAllObservations(emrFileIndex.getInpatNum(), null);
        emrFile.setObservations(observations);
        List<EmrFileData> list = getEmrFileData(emrFileIndex.getEmrFileId(), null);
        List<EmrFileData> topList = buildTreeData(list, null);
        emrFile.setEmrFileDataList(topList);
        return emrFile;
    }

    /**
     * 构造病历数据树
     *
     * @param list                  病历数据
     * @param parentFileIndexDataId 顶级数据节点ID 可以为null
     * @return
     */
    public List<EmrFileData> buildTreeData(List<EmrFileData> list, String parentFileIndexDataId) {
        List<EmrFileData> topList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            EmrFileData node = list.get(i);
            node.setEmrFileDataList(new ArrayList<>());
            if (node.getFileIndexDataEntity().getParentFileIndexDataId() == null
                    || node.getFileIndexDataEntity().getParentFileIndexDataId().equals(parentFileIndexDataId)) {
                node.setPath("");
                topList.add(node);
                continue;
            }
            for (int j = 0; j < i; j++) {
                EmrFileData parent = list.get(j);
                if (parent.getFileIndexDataEntity().getFileIndexDataId().equals(node.getFileIndexDataEntity().getParentFileIndexDataId())) {
                    node.setPath(parent.getPath() + "," + parent.getFileIndexDataEntity().getFileIndexDataId());
                    parent.getEmrFileDataList().add(node);
                    break;
                }
            }
        }
        return topList;
    }

    /**
     * 查询病历数据列表
     *
     * @param emrFileId             病历ID
     * @param parentFileIndexDataId 父级数据ID 可以为null
     * @return
     */
    public List<EmrFileData> getEmrFileData(String emrFileId, String parentFileIndexDataId) {
        long t1 = System.currentTimeMillis();
        //引用病历模板
        List<Map<String, Object>> list = ordersFileIndexMapper.getAllFileIndexDataEntity(emrFileId, parentFileIndexDataId, "0");

        long t2 = System.currentTimeMillis();
        logger.info("{} 从数据库获取{}条数据时间： {} ms", emrFileId, list.size(), t2 - t1);
        List<EmrFileData> emrFileDataList = convertData(list);
        emrFileDataList.stream().forEach(emrFileData -> {
            Element element = emrFileData.getElement();
            // 补充全部勾选项
            if (element.getElementPropertyFormat() != null && element.getElementPropertyFormat().indexOf("\"formatValue\":\"2\"") > -1) {
                element.setSelections(ordersFileIndexMapper.getAllSelections(element.getId()));
            }
        });
        return emrFileDataList;
    }

    private List<EmrFileData> convertData(List<Map<String, Object>> list) {
        return list.parallelStream().map(map -> {
            EmrFileData data = new EmrFileData();
            OrdersFileIndexDataEntity dataEntity = new OrdersFileIndexDataEntity();
            dataEntity.setFileIndexDataId((String) map.get("FILE_INDEX_DATA_ID"));
            try {
                if (map.get("GMT_CREATE") instanceof TIMESTAMP)
                    dataEntity.setCreateTime(((TIMESTAMP) map.get("GMT_CREATE")).timestampValue());
                else
                    dataEntity.setCreateTime((Date) map.get("GMT_CREATE"));
            } catch (SQLException e) {
                logger.error("转换对象出错。", e);
            }
            try {
                if (map.get("GMT_MODIFY") instanceof TIMESTAMP)
                    dataEntity.setModifyTime(((TIMESTAMP) map.get("GMT_MODIFY")).timestampValue());
                else
                    dataEntity.setModifyTime((Date) map.get("GMT_MODIFY"));
            } catch (SQLException e) {
                logger.error("转换对象出错。", e);
            }
            dataEntity.setSortId((map.get("SORT_ID")) == null ? 0 : ((Number) map.get("SORT_ID")).intValue());
            dataEntity.setElementId((String) map.get("ELEMENT_ID"));
            dataEntity.setParentElementId((String) map.get("PARENT_ELEMENT_ID"));
            dataEntity.setQuoteDatasetId((String) map.get("QUOTE_DATASET_ID"));
            dataEntity.setQuoteElementId((String) map.get("QUOTE_ELEMENT_ID"));
            dataEntity.setDataCode(map.get("DATA_CODE") == null ? "" : (String) map.get("DATA_CODE"));
            dataEntity.setParentFileIndexDataId((String) map.get("PARENT_FILE_INDEX_DATA_ID"));
            dataEntity.setBaseTplDetailId((String) map.get("BASE_TPL_DETAIL_ID"));
            dataEntity.setQuoteTplDetailId((String) map.get("QUOTE_TPL_DETAIL_ID"));
            String dataValue = "";
            if (map.get("DATA_VALUE_STR") != null) {
                dataValue = (String) map.get("DATA_VALUE_STR");
            } else {
                try {
                    if (map.get("DATA_VALUE") != null) {
                        if (map.get("DATA_VALUE") instanceof Clob) {
                            Clob clob = (Clob) map.get("DATA_VALUE");
                            BufferedReader reader = new BufferedReader(clob.getCharacterStream());
                            dataValue = FileCopyUtils.copyToString(reader);
                        } else
                            dataValue = (String) map.get("DATA_VALUE");
                    }
                } catch (SQLException | IOException e) {
                    logger.error("转换对象出错。", e);
                }
            }
            dataEntity.setDataValue(dataValue);
            dataEntity.setPrintIdentification((String) map.get("PRINT_IDENTIFICATION"));
            dataEntity.setShowIdentification((String) map.get("SHOW_IDENTIFICATION"));
            dataEntity.setDeleteIdentification((String) map.get("DELETE_IDENTIFICATION"));
            dataEntity.setElementProperty((String) map.get("ELEMENT_PROPERTY"));
            dataEntity.setMedicalId((String) map.get("MEDICAL_ID"));
            dataEntity.setUnit((String) map.get("UNIT"));
            data.setNeedChanged(map.get("NEED_CHANGED") == null ? "1" : map.get("NEED_CHANGED").toString());
            data.setFileIndexDataEntity(dataEntity);
            data.setTplDetailId((String) map.get("TPL_DETAIL_ID"));
            // 补充权限调用属性
            if (map.get("TPL_DETAIL_ROLE_ID") != null) {
                EmrTemplateDetailRoleEntity roleEntity = new EmrTemplateDetailRoleEntity();
                roleEntity.setEditRoleType((String) map.get("EDIT_ROLE_TYPE"));
                roleEntity.setEditRoleId((String) map.get("EDIT_ROLE_ID"));
                roleEntity.setEditDeptId((String) map.get("EDIT_DEPT_ID"));
                roleEntity.setShowRoleType((String) map.get("SHOW_ROLE_TYPE"));
                roleEntity.setShowRoleId((String) map.get("SHOW_ROLE_ID"));
                roleEntity.setShowDeptId((String) map.get("SHOW_DEPT_ID"));
                roleEntity.setPrintRoleType((String) map.get("PRINT_ROLE_TYPE"));
                roleEntity.setPrintRoleId((String) map.get("PRINT_ROLE_ID"));
                roleEntity.setPrintDeptId((String) map.get("PRINT_DEPT_ID"));
                roleEntity.setRefState((String) map.get("REF_STATE"));
                roleEntity.setRefRoleType((String) map.get("REF_ROLE_TYPE"));
                roleEntity.setRefRoleId((String) map.get("REF_ROLE_ID"));
                roleEntity.setRefDeptId((String) map.get("REF_DEPT_ID"));
                data.setRoleEntity(roleEntity);
            }
            // 补充数据元属性
            Element element = new Element();
            element.setId((String) map.get("ELEMENT_ID"));
            element.setName((String) map.get("ELEMENT_NAME"));
            element.setType((String) map.get("ELEMENT_DATA_TYPE_ID"));
            element.setMin(map.get("MIN_VALUE") == null ? null : ((Number) map.get("MIN_VALUE")).doubleValue());
            element.setMax(map.get("MAX_VALUE") == null ? null : ((Number) map.get("MAX_VALUE")).doubleValue());
            element.setUnit(map.get("ELEMENT_UNIT") == null ? null : map.get("ELEMENT_UNIT").toString());
            element.setVarCode((String) map.get("VAR_CODE"));
            element.setMedicalId(dataEntity.getMedicalId());
            element.setFormat((String) map.get("ELEMENT_PROPERTY_FORMAT"));
            element.setElementPropertyFormat((String) map.get("ELEMENT_PROPERTY_FORMAT"));
            element.setIsPreDiag(map.get("IS_PRE_DIAG") == null ? null : map.get("IS_PRE_DIAG").toString());
            data.setElement(element);

            data.setEmrFileDataList(new ArrayList<>());
            return data;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public String saveFileIndex2(EmrFile emrFile) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
//        String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
        String newEmrFileId = UUIDUtil.randomString();
        OrdersFileIndexEntity emrFileIndex = emrFile.getEmrFileIndexEntity();
        if (StringUtils.hasLength(emrFileIndex.getEmrFileId())) {
            OrdersFileIndexEntity originalEmrFileIndex = ordersFileIndexMapper.selectByPrimaryKey(emrFileIndex.getEmrFileId());
            if (!emrFileIndex.getDataVersion().equals(originalEmrFileIndex.getDataVersion())) {
                return ResultGenerator.genFailedResult("当前文件版本和数据库中的版本不一致，无法保存。").getMsg();
            }
        }
        emrFileIndex.setDataVersion(emrFileIndex.getDataVersion() + 1);
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());
        List<EmrFileData> dataList = flatConvert(emrFile.getEmrFileDataList());
        //查询模板
        EmrTemplateEntity tpl = templateMapper.selectByPrimaryKey(emrFileIndex.getTplId());
        //查询目录
        EmrCatalogEntity catalog = emrCatalogMapper.selectByPrimaryKey(tpl.getCtlId());
        if (!StringUtils.hasLength(emrFileIndex.getEmrFileId())) {//新建
            emrFileIndex.setEmrFileId(newEmrFileId);
            emrFileIndex.setGmtCreate(currentTime);
            emrFileIndex.setGmtModify(currentTime);
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(userId)){
                emrFileIndex.setNurseId(userId);
            }
            if (tpl == null) {
                throw new ServiceException("模板已不存在，无法保存。");
            }
            if (catalog == null)
                throw new ServiceException("病历目录已不存在，无法保存。");

            ordersFileIndexMapper.insertSelective(emrFileIndex);
        } else {//更新
            emrFileIndex.setGmtModify(currentTime);
            newEmrFileId = emrFileIndex.getEmrFileId();
            ordersFileIndexMapper.updateByPrimaryKeySelective(emrFileIndex);
        }
        if (emrFileIndex.getDataVersion() > 1) {
            long t1 = System.currentTimeMillis();
            ordersFileIndexMapper.recordBeforeUpdate(emrFileIndex.getEmrFileId());
            long t2 = System.currentTimeMillis();
            logger.info("{} 记录耗时：{} ms", emrFileIndex.getEmrFileId(), t2 - t1);
        }


        long t1 = System.currentTimeMillis();
//            SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH);
//            Map<String, Object> params = new HashMap<>();
//            params.put("fileIndex", emrFileIndex);
        String finalNewEmrFileId = newEmrFileId;
        List<OrdersFileIndexDataEntity> ordersFileIndexDataEntities = dataList.stream().map(data -> data.getFileIndexDataEntity()).map(dataEntity -> {
            dataEntity.initAdd();
            dataEntity.setDataVersion(emrFileIndex.getDataVersion());
            dataEntity.setEmrFileId(finalNewEmrFileId);
            dataEntity.setFileIndexDataId(UUIDUtil.randomString());
            return dataEntity;
//                params.put("dataEntity", dataEntity);
//                session.insert("com.haoze.nurseapp.dao.OrdersFileIndexDataMapper.insertDataListWithIndependentClob", params);
        }).collect(Collectors.toList());
        ordersFileIndexDataMapper.removeDeletedNodes(finalNewEmrFileId, -1);
        logger.info("===============重新新增文书{}",JSONUtils.beanToJson(ordersFileIndexDataEntities));
        if(!CollectionUtils.isEmpty(ordersFileIndexDataEntities)) {
            ordersFileIndexDataMapper.insertAllFileIndexData(ordersFileIndexDataEntities);
        }
//            session.flushStatements();
//            session.close();
        long t2 = System.currentTimeMillis();
        logger.info("{} 明细存储耗时：{} ms", emrFileIndex.getEmrFileId(), t2 - t1);
        return newEmrFileId;
    }

    @Override
    @Transactional
    public String saveFileIndex(EmrFile emrFile) {
        String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
//        String userId = "bf533ba10ec64ab0bbf360c44fa7a787";
        String newEmrFileId = UUIDUtil.randomString();
        try {
            OrdersFileIndexEntity emrFileIndex = emrFile.getEmrFileIndexEntity();
            if (StringUtils.hasLength(emrFileIndex.getEmrFileId())) {
                OrdersFileIndexEntity originalEmrFileIndex = ordersFileIndexMapper.selectByPrimaryKey(emrFileIndex.getEmrFileId());
                if (!emrFileIndex.getDataVersion().equals(originalEmrFileIndex.getDataVersion())) {
                    return ResultGenerator.genFailedResult("当前文件版本和数据库中的版本不一致，无法保存。").getMsg();
                }
            }
            emrFileIndex.setDataVersion(emrFileIndex.getDataVersion() + 1);
            Timestamp currentTime = new Timestamp(System.currentTimeMillis());
            List<EmrFileData> dataList = flatConvert(emrFile.getEmrFileDataList());
            //查询模板
            EmrTemplateEntity tpl = templateMapper.selectByPrimaryKey(emrFileIndex.getTplId());
            //查询目录
            EmrCatalogEntity catalog = emrCatalogMapper.selectByPrimaryKey(tpl.getCtlId());
            if (!StringUtils.hasLength(emrFileIndex.getEmrFileId())) {//新建
                emrFileIndex.setEmrFileId(newEmrFileId);
                emrFileIndex.setGmtCreate(currentTime);
                emrFileIndex.setGmtModify(currentTime);
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(userId)){
                    emrFileIndex.setNurseId(userId);
                }
                if (tpl == null) {
                    throw new ServiceException("模板已不存在，无法保存。");
                }
                if (catalog == null)
                    throw new ServiceException("病历目录已不存在，无法保存。");

                ordersFileIndexMapper.insertSelective(emrFileIndex);
            } else {//更新
                emrFileIndex.setGmtModify(currentTime);
                newEmrFileId = emrFileIndex.getEmrFileId();
                ordersFileIndexMapper.updateByPrimaryKeySelective(emrFileIndex);
            }
            if (emrFileIndex.getDataVersion() > 1) {
                long t1 = System.currentTimeMillis();
                ordersFileIndexMapper.recordBeforeUpdate(emrFileIndex.getEmrFileId());
                long t2 = System.currentTimeMillis();
                logger.info("{} 记录耗时：{} ms", emrFileIndex.getEmrFileId(), t2 - t1);
            }


            long t1 = System.currentTimeMillis();
            SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH);
            Map<String, Object> params = new HashMap<>();
            params.put("fileIndex", emrFileIndex);
//            for (EmrFileData emrFileData:dataList) {
//                OrdersFileIndexDataEntity dataEntity = emrFileData.getFileIndexDataEntity();
//
//            }
            dataList.stream().map(data -> data.getFileIndexDataEntity()).forEach(dataEntity -> {
                params.put("dataEntity", dataEntity);
                session.insert("com.haoze.nurseapp.dao.OrdersFileIndexDataMapper.insertDataListWithIndependentClob", params);
            });
            session.flushStatements();
            session.close();
            ordersFileIndexDataMapper.removeDeletedNodes(emrFileIndex.getEmrFileId(), emrFileIndex.getDataVersion());
            long t2 = System.currentTimeMillis();
            int count = ordersFileIndexDataMapper.selectCountByTest(newEmrFileId, emrFileIndex.getDataVersion());
            logger.info("{} 明细存储耗时：{} ms,count============{}", emrFileIndex.getEmrFileId(), t2 - t1,count);
        } catch (ServiceException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "";
        } catch (Exception e) {
            logger.error("保存病历出错。", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "";
        }
        return newEmrFileId;
    }

    public Map<String, String> getCurrentUser() {
        String userId = "";
        try {
            userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                    .getHeader("zuul_id");
        } catch (Exception e) {
            //后台创建，创建人设成admin
            Map<String, String> admin = ordersFileIndexMapper.getSysUser("admin");
            userId = admin.get("userId");
        }
        Map<String, String> currentUser = ordersFileIndexMapper.getUser(userId);
        if (currentUser == null)
            return new HashMap<String, String>();
        return currentUser;
    }

    @Override
    public Result createFileIndex(String tplId, String inpatNum, String wardDeptId, String reqNum, String serialNo,String refEmrFileId,String dailyAssessmentMarker) {
        Map<String, String> patientInfo = ordersFileIndexMapper.getPatientInfo(inpatNum);
        if (patientInfo == null) {
            return ResultGenerator.genFailedResult("住院号不存在，无法创建病历。");
        }
        EmrFile emrFile = new EmrFile();
        EmrTemplateEntity tpl = emrTemplateMapper.selectByPrimaryKey(tplId);
        if (tpl == null) {
            return ResultGenerator.genFailedResult("模板不存在，无法创建病历。");
        }
        OrdersFileIndexEntity emrFileIndex = new OrdersFileIndexEntity();
        emrFileIndex.setDataVersion(0);
        Map<String, String> currentUser = getCurrentUser();
        String userName = currentUser.get("userName");
        if (!StringUtils.hasLength(userName)) {
            userName = "无名";
        }
        emrFile.setUserName(userName);
        String groupName = currentUser.get("groupName");
        emrFile.setGroupName(groupName);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
        String emrFileName = tpl.getTplName() + "—" + userName + "—" + sdf.format(new Date(System.currentTimeMillis()));
        emrFileIndex.setEmrFileName(emrFileName);
        emrFileIndex.setHospitalId(tpl.getHospitalId());
        emrFileIndex.setOutpatNum("0");
        emrFileIndex.setInpatNum(inpatNum);
        emrFileIndex.setWardDeptId(wardDeptId);
        EmrCatalogEntity catalog = emrCatelogMapper.selectByPrimaryKey(tpl.getCtlId());
        emrFile.setEmrType(catalog.getEmrType());
        emrFile.setPrintType(catalog.getPrintType());
        emrFileIndex.setDelFlag(NurseFileIndexService.NOT_DELETE);
        emrFileIndex.setTplId(tpl.getTplId());
        if (ONLY_ONE.equals(catalog.getCreateMode())) { // 需要检查模板文书的唯一性
            int cnt = ordersFileIndexMapper.getFileCnt(inpatNum, tplId);
            if (cnt > 0) {
                return ResultGenerator.genFailedResult("同样的病历已经存在，不能再次创建新病历。");
            }
        }
        emrFile.setEmrFileIndexEntity(emrFileIndex);
        //模板中的引用数据集
        List<CompletableFuture<Tuple2<String, JSONObject>>> datasetFutures = getDatasetMap(tpl.getTplId(), inpatNum, reqNum, serialNo, catalog.getEmrType());
        //模板中的自引用
        List<Map<String, String>> observations = ordersFileIndexMapper.queryAllObservations(emrFileIndex.getInpatNum(), tplId);
        emrFile.setObservations(observations);

        List<EmrFileData> dataList = createEmrFileData(emrFileIndex, datasetFutures, patientInfo, catalog,refEmrFileId,dailyAssessmentMarker);
        dataList.stream().filter(data -> NurseFileIndexService.WENJIANTAITOU_RQSJ.equals(data.getElement().getVarCode())).forEach(data -> {
            data.getFileIndexDataEntity().setDataValue(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date(System.currentTimeMillis())));
        });
        List<EmrFileData> topList = buildTreeData(dataList, "");
        /*if(!CollectionUtils.isEmpty(topList)){
            for(EmrFileData efd:topList){
                List<EmrFileData> efdList = efd.getEmrFileDataList();
                List<EmrFileData> newEfdList = efd.getEmrFileDataList();
                if(efdList!=null && efdList.size()>1){
                    for(EmrFileData ef:efdList){
                        OrdersFileIndexDataEntity fileIndexDataEntity = ef.getFileIndexDataEntity();
                        if(CommonUtils.isNotEmpty(fileIndexDataEntity.getDataValue())){
                            newEfdList.add(ef);
                        }
                    }
                    efd.setEmrFileDataList(newEfdList);
                }
            }
        }*/
        emrFile.setEmrFileDataList(topList);
        Map attributes = new HashMap();
        attributes.put("ctlName", catalog.getCtlName());
        attributes.put("emrType", catalog.getEmrType());
        emrFile.setAttributes(attributes);
        return ResultGenerator.genOkResult(emrFile);
    }

    @Override
    public List<Map<String,String>> getSpeedUnit() {
        return ordersFileIndexMapper.getSpeedUnit();
    }

    @Override
    public Result getFileByQrCode(String qrCode) {
        NodeInfoDTO nodeInfoDTO = taskExecuteMapper.queryWaitExecuteNode(qrCode);
        if (nodeInfoDTO == null) {
            return ResultGenerator.genOkResult();
        }
        EmrFile emrFile = getFileIndex(nodeInfoDTO.getEmrFileId());
        Map<String, Object> map = new HashMap<>();
        map.put("emrFile", emrFile);
        map.put("qrCode", qrCode);
        map.put("taskNodeId", nodeInfoDTO.getTaskNodeId());
        return ResultGenerator.genOkResult(map);
    }

    private List<EmrFileData> createEmrFileData(OrdersFileIndexEntity emrFileIndex,
                                                List<CompletableFuture<Tuple2<String, JSONObject>>> datasetFeatures,
                                                Map<String, String> patientInfo, EmrCatalogEntity catalog,String refEmrFileId,String dailyAssessmentMarker) {

        long t1 = System.currentTimeMillis();
        List<Map<String, Object>> list = ordersFileIndexMapper.createEmrFileData(emrFileIndex);
        long t2 = System.currentTimeMillis();
        logger.info("{} 模板{}条查询时间：{} ms", emrFileIndex.getTplId(), list.size(), t2 - t1);
        List<EmrFileData> emrFileDataList = convertData(list);
        Map<String, Map<String, Object>> datasetMap = new HashMap<>();
        try {
            CompletableFuture.allOf(datasetFeatures.toArray(new CompletableFuture[datasetFeatures.size()])).thenApply(v -> {
                return datasetFeatures.stream().map(datasetFeature -> datasetFeature.join())
                        .collect(Collectors.toList());
            }).get().stream().filter(tuple2 -> tuple2 != null).forEach(tuple2 -> {
                datasetMap.put(tuple2.getT1(), tuple2.getT2());
            });
        } catch (Exception e) {
            logger.error("查询第三方接口出现错误。", e);
        }
        int orignialSize = emrFileDataList.size();
        for (int i = 0; i < orignialSize; i++) {
            EmrFileData emrFileData = emrFileDataList.get(i);
            OrdersFileIndexDataEntity dataEntity = emrFileData.getFileIndexDataEntity();
            String oldId = dataEntity.getFileIndexDataId();
            String newId = UUIDUtil.randomString();
            dataEntity.setFileIndexDataId(newId);
            Element element = emrFileData.getElement();

            // 引用数据集
            if (StringUtils.hasLength(dataEntity.getQuoteDatasetId()) && StringUtils.hasLength(dataEntity.getQuoteElementId())) {
                updateQuoteDatasetValue(datasetMap, emrFileData, true);
            }
            // 补充全部勾选项
            if (element.getElementPropertyFormat() != null && element.getElementPropertyFormat().indexOf("\"formatValue\":\"2\"") > -1) {
                element.setSelections(ordersFileIndexMapper.getAllSelections(element.getId()));
            }

            // 引用其他病历 新版本
            if (StringUtils.hasLength(dataEntity.getQuoteTplDetailId()) && dataEntity.getQuoteTplDetailId().startsWith("[[")) {
                JSONArray priorityArray = JSONArray.parseArray(dataEntity.getQuoteTplDetailId());
                for (Object priorityObj : priorityArray) {
                    JSONArray totalArray = (JSONArray) priorityObj;
                    boolean isFound = totalArray.stream().map(parallelingObj -> {
                        JSONObject quoteRule = (JSONObject) parallelingObj;
                        String emrType = quoteRule.getString("emrType");
                        List<OrdersFileIndexDataEntity> refDataList=null;
                        if (StringUtils.isEmpty(emrType)) {
                            String quoteCtlId = quoteRule.getString("quoteCtlId");
                            //logger.info("缺少目录类型，无法引用。");
                            //return false;
                            if (StringUtils.isEmpty(quoteCtlId)) {
                                logger.info("缺少目录和医嘱，无法引用。");
                                return false;
                            }else{
                                if (StateEnum.CATALOG_ORDERS.getValue().equals(quoteRule.getString("quoteNodeType"))) {
                                    /*if (taskExecuteEntity != null) { // 引用本次医嘱
                                        Map<String, String> fileDataByOrder = emrFileMapper.getFileDataByOrder(taskExecuteEntity.getInpatorderdataId());
                                        String inpatorderdataId = taskExecuteEntity.getInpatorderdataId();
                                        if(org.apache.commons.lang3.StringUtils.isNotBlank(fileDataByOrder.get("fileIndexDataId"))){
                                            inpatorderdataId =fileDataByOrder.get("fileIndexDataId");
                                        }
                                        refDataList = emrFileMapper.queryRefOrderData(quoteRule.getString("quoteId"), inpatorderdataId, emrFileIndex.getInpatNum(),
                                                quoteRule.getString("quoteAll"), quoteRule.getString("isDesc"), fileDataByOrder.get("emrFileId"), fileDataByOrder.get("elementId"));
                                    } else { // 开医嘱时引用上次医嘱
                                        refDataList = emrFileMapper.queryRefLastOrderData(quoteRule.getString("quoteId"), quoteCtlId, emrFileIndex.getInpatNum());
                                    }*/
                                    if("dailyAssessmentMark".equals(dailyAssessmentMarker)){
                                        if(!StringUtils.isEmpty(refEmrFileId)){
                                            refDataList = ordersFileIndexMapper.queryRefDataByEmrFileId(refEmrFileId,quoteRule.getString("quoteId"));
                                        }
                                    }else{
                                        // 开医嘱时引用上次医嘱
                                        refDataList = ordersFileIndexMapper.queryRefLastOrderData(quoteRule.getString("quoteId"), quoteCtlId, emrFileIndex.getInpatNum());
                                    }
                                } else {
                                    if("dailyAssessmentMark".equals(dailyAssessmentMarker)){
                                        if(!StringUtils.isEmpty(refEmrFileId)){
                                            refDataList = ordersFileIndexMapper.queryRefDataByEmrFileId(refEmrFileId,quoteRule.getString("quoteId"));
                                        }
                                    }else{
                                        refDataList = ordersFileIndexMapper.queryRefDataByCtlId(quoteRule.getString("quoteId"), quoteCtlId, emrFileIndex.getInpatNum(), quoteRule.getString("quoteAll"), quoteRule.getString("isDesc"));

                                    }
                                }
                            }
                        }else{
                            if("dailyAssessmentMark".equals(dailyAssessmentMarker)){
                                if(!StringUtils.isEmpty(refEmrFileId)){
                                    refDataList = ordersFileIndexMapper.queryRefDataByEmrFileId(refEmrFileId,quoteRule.getString("quoteId"));
                                }
                            }else{
                                refDataList = ordersFileIndexMapper.queryRefData(quoteRule.getString("quoteId"), emrType, emrFileIndex.getInpatNum(), quoteRule.getString("quoteAll"), null);
                            }
                        }

                        //List<OrdersFileIndexDataEntity> refDataList = ordersFileIndexMapper.queryRefData(quoteRule.getString("quoteId"), emrType, emrFileIndex.getInpatNum(), quoteRule.getString("quoteAll"), null);
                        if (refDataList==null || refDataList.isEmpty()) { // 引用节点已不存在 忽略
                            return false;
                        }
                        //return IntStream.range(0, refDataList.size()).mapToObj(idx -> {
                        List<OrdersFileIndexDataEntity> finalRefDataList = refDataList;
                        return IntStream.range(0, finalRefDataList.size()).mapToObj(idx -> {
                            //OrdersFileIndexDataEntity refData = refDataList.get(idx);
                            OrdersFileIndexDataEntity refData = finalRefDataList.get(idx);
                            if ("Y".equals(quoteRule.getString("oneToOne"))) { // 点对点引用
                                if (StringUtils.isEmpty(refData.getDataValue())) {
                                    return false;
                                }
                                dataEntity.setDataValue(refData.getDataValue());
                                dataEntity.setDataCode(refData.getDataCode());
                                return true; // 有数据 才算找到
                            }
                            // 引用下级节点
                            long t3 = System.currentTimeMillis();
                            List<EmrFileData> refList = getEmrFileData(refData.getEmrFileId(), refData.getFileIndexDataId());

                            List<EmrFileData> newRefList = new CopyOnWriteArrayList<>();
                            Map<String, Object> elementPropertyMap = JSONUtils.jsonToMap(refData.getElementProperty());
                            if(elementPropertyMap.get("isReplaceCurrentContent")!=null && elementPropertyMap.get("isReplaceCurrentContent").equals("0")){
                                if(!CollectionUtils.isEmpty(refList)){
                                    for(EmrFileData ref:refList){
                                        OrdersFileIndexDataEntity fileIndexDataEntity = ref.getFileIndexDataEntity();
                                        String dataValue = fileIndexDataEntity.getDataValue();
                                        String elementId = fileIndexDataEntity.getElementId();
                                        if(CommonUtils.isNotEmpty(dataValue)){
                                            for(int o=0;o<emrFileDataList.size();o++){
                                                EmrFileData efd=emrFileDataList.get(o);
                                                System.out.println("elementId="+elementId);
                                                System.out.println("tpldetailId="+efd.getTplDetailId());
                                                if(!StringUtils.isEmpty(efd.getTplDetailId())) {
                                                    if (elementId.equals(efd.getFileIndexDataEntity().getElementId()) && efd.getTplDetailId().equals(ref.getTplDetailId())) {
                                                        emrFileDataList.remove(o);
                                                        o--;
                                                        //break;
                                                    }
                                                }
                                            }
                                        }else{
                                            for(int o=0;o<emrFileDataList.size();o++){
                                                EmrFileData efd=emrFileDataList.get(o);
                                                if(!StringUtils.isEmpty(efd.getTplDetailId())) {
                                                    if (elementId.equals(efd.getFileIndexDataEntity().getElementId()) && efd.getTplDetailId().equals(ref.getTplDetailId())) {
                                                        emrFileDataList.remove(o);
                                                        o--;
                                                        //break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }

                            long t4 = System.currentTimeMillis();
                            logger.info("被引用病历{}条查询时间：{} ms", refList.size(), t4 - t3);
                            if (refList.isEmpty()) { // 无子节点 也算找到了
                                return true;
                            }
                            String type = quoteRule.getString("type");
                            if ("2".equals(type)) { // 医疗术语 引用节点本身也添加进去
                                EmrFileData tempData = new EmrFileData();
                                Element tempElement = new Element();
                                tempElement.setType("20");
                                tempData.setElement(tempElement);
                                tempData.setFileIndexDataEntity(refData);
                                refList.add(0, tempData);
                            }
                            for (int j = 0; j < refList.size(); j++) {
                                EmrFileData subRefData = refList.get(j);
                                subRefData.setFirstQuote(true); // 标记为第一次引用 提示前端不要进行自引用修改
                                OrdersFileIndexDataEntity refDataEntity = subRefData.getFileIndexDataEntity();
                                if ("2".equals(type)) {
                                    if (refDataEntity == refData) { // 医疗术语本身
                                        refDataEntity.setParentFileIndexDataId(newId);
                                    }
                                } else {
                                    if (refDataEntity.getParentFileIndexDataId().equals(refData.getFileIndexDataId())) {
                                        refDataEntity.setParentFileIndexDataId(newId);
                                    }
                                }

                                String subOldId = refDataEntity.getFileIndexDataId();
                                String subNewId = UUIDUtil.randomString();
                                refDataEntity.setFileIndexDataId(subNewId);
                                refDataEntity.setCreateTime(dataEntity.getCreateTime());
                                refDataEntity.setModifyTime(dataEntity.getModifyTime());
                                try {
                                    String elementProperty = refDataEntity.getElementProperty();
                                    JSONObject jsonObject = JSONObject.parseObject(elementProperty);
                                    jsonObject.put("printNewLine", "1");
                                    jsonObject.put("childPrintNewLine", "1");
                                    jsonObject.put("printAlign", "0");
                                    jsonObject.put("printFontBold", "1");
                                    jsonObject.put("printSplitLine", "1");
                                    jsonObject.put("childrenPrintAlign", "0");
                                    jsonObject.put("selfPrintAlign", "0");
                                    if (idx != 0 && j == 0) { // 第一项增加一个换行符号
                                        jsonObject.put("newLine", "0");
                                        jsonObject.put("printNewLine", "0");
                                    }
                                    refDataEntity.setElementProperty(jsonObject.toJSONString());
                                } catch (Exception e) {
                                    logger.error("重置elementProperty出错。", e);
                                }
                                for (int k = j; k < refList.size(); k++) {
                                    EmrFileData subNextData = refList.get(k);
                                    OrdersFileIndexDataEntity subNextDataEntity = subNextData.getFileIndexDataEntity();
                                    if (subOldId.equals(subNextDataEntity.getParentFileIndexDataId())) {
                                        subNextDataEntity.setParentFileIndexDataId(subNewId);
                                    }
                                }
                            }

                            emrFileDataList.addAll(refList);
                            }
                            return true;
                        }).reduce(false, (accumulatorBoolean, nextBoolean) -> accumulatorBoolean || nextBoolean);

                    }).reduce(false, (accumulatorBoolean, nextBoolean) -> accumulatorBoolean || nextBoolean);
                    // 如果已经引用到数据 终止循环
                    if (isFound) {
                        break;
                    }
                }
            }
            // 补充父级ID
            for (int j = i + 1; j < orignialSize; j++) {
                EmrFileData nextData = emrFileDataList.get(j);
                if (oldId.equals(nextData.getFileIndexDataEntity().getParentFileIndexDataId())) {
                    nextData.getFileIndexDataEntity().setParentFileIndexDataId(newId);
                }
            }
        }
        Map<String, String> currentUser = getCurrentUser();
        return emrFileDataList.parallelStream().filter(emrFileData -> {
            Element element = emrFileData.getElement();
            if ("wenjiantaitou-rqsj".equals(element.getVarCode())) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                emrFileData.getFileIndexDataEntity().setDataValue(sdf.format(new Date(System.currentTimeMillis())));
            }
            if ("手术名称".equals(element.getName()) && "手术名称".equals(emrFileData.getFileIndexDataEntity().getDataValue())) {
                emrFileData.getFileIndexDataEntity().setDataValue("-");
            }
            return true;
        }).collect(Collectors.toList());
    }

    private void updateQuoteDatasetValue(Map<String, Map<String, Object>> datasetMap, EmrFileData emrFileData, boolean trigger) {
        OrdersFileIndexDataEntity dataEntity = emrFileData.getFileIndexDataEntity();
        Element element = emrFileData.getElement();
        Map<String, Object> dataset = datasetMap.get(dataEntity.getQuoteDatasetId());
        if (dataset != null) {
            Object value = dataset.get(dataEntity.getQuoteElementId());
            if (value != null) {
                switch (element.getType()) {
                    case TYPE_SIGNLE_SELECTION:
                    case TYPE_MULTIPLE_SELECTION:
                        try {
                            String[] dataPair = value.toString().split(NurseFileIndexService.SPECIAL_SPLITER);
                            if (dataPair.length == 2) {
                                dataEntity.setDataCode(dataPair[0]);
                                dataEntity.setDataValue(dataPair[1]);
                                emrFileData.setFirstTrigger(trigger);
                            } else {
                                // 麻醉方法代码只能返回文本
                                dataEntity.setDataValue(value.toString().replaceAll("\\$€\\$€\\$", ""));
                            }
                        } catch (Exception e) {
                            logger.error("赋值出错。", e);
                        }
                        break;
                    default:
                        dataEntity.setDataValue(value.toString());
                }
            }
        }
    }
}
